<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="about">
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索技能名称"
            enter-button="搜索"
            @search="handleSearch"
        />
        <a-button type="primary" @click="showModal">
          新增
        </a-button>
      </a-space>
      <a-table
          :columns="columns"
          :row-key="item => item.skillId"
          :data-source="jobSkills"
          :pagination="pagination"
          :loading="isLoading"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="showModal(record)">
                编辑
              </a-button>
              <a-popconfirm
                  title="是否确认要删除?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="deleteSkill(record)"
              >
                <a-button danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </a-layout-content>

  <!-- 模态框 - 编辑 -->
  <a-modal v-model:open="open" title="编辑技能标签" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form ref="editForm" :model="selectedSkill" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="技能名称" name="skillName">
        <a-input v-model:value="selectedSkill.skillName" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue';

// 类型定义
interface JobSkill {
  skillId: number;
  skillName: string;
}

// 分页数据
const pagination = ref({
  pageSize: 10,
  total: 0,
  current: 1
});

// 技能列表
const jobSkills = ref<JobSkill[]>([]);
const isLoading = ref(true);

// 搜索关键词
const searchKeyword = ref('');
const isSearch = ref(false);

// 弹窗状态
const open = ref(false);
const confirmLoading = ref(false);

// 编辑选中项
const selectedSkill = ref<JobSkill>({
  skillId: 0,
  skillName: ''
});

// 表格列定义
const columns = [
  {
    title: '技能名称',
    dataIndex: 'skillName',
    width: 200,
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center' as const,
    width: 150,
  }
];

interface PaginationParams {
  current: number;
  pageSize: number;
}

// 分页逻辑
const handleTableChange = (pag: PaginationParams) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;

  if (!isSearch.value) {
    fetchSkills();
  } else {
    handleSearch();
  }

  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 获取技能列表
const fetchSkills = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/jobskills/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;

    pagination.value.total = res.data.data.total;
    jobSkills.value = res.data.data.list;

    if (jobSkills.value.length === 0 && pagination.value.current > 1) {
      pagination.value.current--;
      fetchSkills();
    }
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

onMounted(async () => {
  await fetchSkills();
});

// 显示编辑弹窗
const showModal = (record: JobSkill) => {
  // message.success(record.skillId);
  open.value = true;
  selectedSkill.value = { ...record };
};

// 删除技能
const deleteSkill = (record: JobSkill) => {
  axios.post('/jobskills/delete', {
    skillId: record.skillId
  }).then(() => {
    if (!isSearch.value) {
      fetchSkills();
    } else {
      handleSearch();
    }
    message.success('删除技能成功');
  }).catch(() => {
    message.error('删除技能失败');
  });
};

// 编辑提交
const handleOk = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 500);

  axios.post('/jobskills/update', selectedSkill.value)
      .then(res => {
        if (res.data.code === 200) {
          fetchSkills();
          message.success('更新成功');
        } else {
          message.error('更新失败');
        }
      })
      .catch(err => {
        console.error('更新失败:', err);
        message.error('更新失败，请重试');
      });
};


// 搜索逻辑
const handleSearch = () => {
  axios.post('/jobskills/query', {
    skillName: searchKeyword.value
  }).then(res => {
    isSearch.value = true;
    pagination.value.total = res.data.data.length;
    jobSkills.value = res.data.data;
    isLoading.value = false;
  }).catch(err => {
    console.error('搜索失败:', err);
    isLoading.value = false;
  });
};

</script>
